﻿using Castle.Core.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace Inovout.YunYao.Cattle.WindowsService
{
    /// <summary>
    /// 数据黄牛
    /// 有如下几种工作模式：
    /// 1、永远工作
    /// 2、指定队列范围
    /// </summary>
    public class DataCattle
    {
        private ILogger logger;
        //private AutoResetEvent dataConveyorEvent;
        public Thread Thread { get; internal set; }
        private PersistentTask task;
        public DataCattle(PersistentTask task)
        {
            logger = ComponentRegistry.Resolve<ILogger>();
            this.task = task;
            task.DataCattle = this;
            //dataConveyorEvent = new AutoResetEvent(true);
            dataConveyor = new DataConveyor(task.HBaseIP, task.HBasePort, task.HBaseTableNamePrefix);
            queueManager = new QueueManager(task.RedisIP,
               task.RedisPort, task.RedisTableId, task.QueueName);

        }
        private DataConveyor dataConveyor;
        private QueueManager queueManager;
        public int Do(int start, int stop)
        {
            string[] queues = queueManager.Receive(start, stop);
            int queueCount = queues.Length;
            //dataConveyorEvent.WaitOne();
            if (queueCount > 0)
            {
                dataConveyor.Push(queues);
                queueManager.Remove(start, stop).Wait();
            }
            //dataConveyorEvent.Reset();
            return queueCount;
        }
        public void Do()
        {
            while (true)
            {
                //不能按配置批处理数据删除队列，因为可能队列数量少于默认处理的队列数量，故还需获取共获取了多少个队列数量，以这个数量去移除。
                int queueCount = this.Do(0, task.BatchCount-1);
                if (queueCount > 0)
                {
                    logger.InfoFormat("已处理{0}中{1}个数据", task.QueueName, queueCount.ToString());
                }
            }
        }
    }
}
